<?php
/*
 * 情报中心数据结构
 * json格式
 * {
 *  logtype:情报类型,1、普通内容，只需设置已读状态；
 *                  2、设置已读状态，之后需要跳转到某个链接；
 *  url:[url1,url2...]跳转url
 *  text:消息正文
 * }
 */
//情报类型常量类
//情报类型可以总结为：1、普通内容，只需设置已读状态；
//                   2、设置已读状态，之后需要跳转到某个链接；
class LogType {
    static $OLDVERION=0;
    
    static $NORMAL=101;//普通类型
    static $REDIRECT=102;//跳转
}
//Team Action
class TeamAction extends TeamBaseAction {
    
    static private $LOGTYPE = array(
        'OLDVERSION' => 0,
        'TEAM_INVENTION' => 1,//团队邀请
    );

    public function _empty() {
        $tpl = "../Include/App/Group/Bridge/Tpl/Public_404.html";
        $this->display($tpl);
    }

    public function __construct() {
        parent::__construct();
        $this->assign('on',1);
    }
    
    //用户入队时同步数据
    private function jointeam_syncdata($uid, $pid, $did, $jobid) {
        $resPrj = M('project')->where('id='.$pid.' and state>0')->find();
        $teamid = $resPrj['tid'];
        $resTeam = M('team')->where('id='.$teamid.' and state>0')->find();
        $teamdata = array(
            'teamname' => $resTeam['name'],
            'teamid' => $teamid,
            'projectname' => $resPrj['name'],
            'projectid' => $pid,
        );
        $ret = M('user_info')->where('uid='.$uid)->save($teamdata);
        $userinfo = $this->userinfo;
        $userinfo['teamname'] = $teamdata['teamname'];
        $userinfo['teamid'] = $teamdata['teamid'];
        $userinfo['projectname'] = $teamdata['projectname'];
        $userinfo['projectid'] = $teamdata['projectid'];
        $this->userinfo = $userinfo;
        if (!$ret) {
            Log::write('[jointeam]同步用户数据失败', Log::ERR);
            return 0;
        }

        //同步职位统计
        M('job')->where('id='.$jobid)->setInc('datastate');
        setTeamJobNum($teamid, 0, 1);
        
        //同步任职记录
        $now = time();
        $job = M('job')->where('id='.$jobid)->find();
        $hisdata = array(
            'uid' => $uid,
            'jobid' => $jobid,
            'prjid' => $pid,
            'teamid' => $teamid,
            'jointime' => $now,
            'quitime' => '0',
            'quitype' => \App\Common\Constvars::JOBHIS_QUITYPE_UNQUIT,
        );
        M('jobhistory')->add($hisdata);
        
        return $teamid;
    }

    private function showBaseinfo($tplName) {
        $uid = $this->uid;
        if (!$uid) {
            $this->redirect('/@'.getDomain());
        }
        $this->userinfo = M('user_info')->where("uid=" . $uid)->find();
        $table = array('xia_team'=>'team');
        $join = "xia_project prj on team.id=prj.tid";
        $field = "team.*, prj.name as pname, prj.abstract as pabstract";
        $where = 'team.uid='.$uid.' and team.state>0';
        $teamRes = M('team')->table($table)->field($field)->where($where)->join($join)->find();
        $creater = 0;
        $editor = 0;//编辑团队信息权限
        if ($teamRes) {
            $creater = 1;//是团队创建者
            $this->assign("arr", $teamRes);
        } else {
            $where = "team.id=" . $this->userinfo['teamid'].' and team.state>0';
            $teamRes2 = M('team')->table($table)->field($field)->where($where)->join($join)->find();
            if ($teamRes2) {
                $this->assign("arr", $teamRes2);
            }
            //是否有编辑团队信息权限
            $resJobuser = M('job_user')->where('uid='.$uid.' and state=2')->find();
            $resAuth = M('authdispatch')->where('arid='.$resJobuser['id'].' and authid=50')->select();
            if($resAuth){
                $editor = 1;
            }
        }
        $this->assign("uid", $uid);
        $this->assign("userinfo", $this->userinfo);

        $this->assign("creater", $creater);
        $this->assign('editor', $editor);
        
        $this->assign('teamsubon', 1);
        $this->display($tplName);
    }
    
    public function index() {
        $this->userinfo = M('user_info')->where('uid='.$this->uid)->find();
        if (!$this->userinfo['teamid'] || $this->userinfo['teamid']<=0) {
            $this->dataheader();
            $this->display('createjoin');
        } else {
            $this->redirect("Team/main@".getDomain());//若已有团队,则优先跳转到项目管理页
        }
    }
    
    //main页
    public function main() {
        $resTeam = M('team')->where('id='.$this->userinfo['teamid'].' and state>0')->find();
        if($resTeam){
            $this->assign('team', $resTeam);
        }
        
        $this->dataheader();
        $this->display();
    }

    //权限管理
    public function Authorization() {
        $id = I('teamid');
        if (!$id) {
            $this->redirect('/@'.getDomain());
        }
        
        //权限校验
        $ret = parent::isTeamCreater($id);
        if(!$ret){
            $this->redirect('/@'.getDomain());
        }
        else{
            $this->assign('creater', 1);
        }
        
        $tabs = array('xia_job_user'=>'ju', 'xia_user_info'=>'uif');
        $field = 'ju.id, uif.uid, uif.nickname';
        $where = 'ju.pid='.$this->userinfo['projectid'].' and ju.state in (2,4,5) and ju.uid=uif.uid';
        $authroles = M('job_user')->table($tabs)->field($field)->where($where)->select();
        $this->assign('roles', $authroles);
        
        $this->assign('teamsubon', 5);
        
        $this->dataheader();
        
        $this->display();
    }

    //创建&编辑团队
    public function baseinfo() {
        $this->dataheader();
        $this->showBaseinfo("baseinfo");
    }

    //提交团队基本信息
    public function teaminfo_ajax() {
        //权限校验
        //是否团队创建者
        if($this->userinfo['teamid']>-1){
            $resTeam = parent::isTeamCreater($this->userinfo['teamid']); //M('team')->where('uid='.$this->uid.' and state>0')->find();
            if(!$resTeam){//不是创建者
                $resAuth = parent::teamauthcheck($this->uid, 50); //M('authdispatch')->where('arid='.$this->userinfo['role'].' and authid=50')->select();
                if(!$resAuth){
                    echo json_encode(array('success' => 0, 'msg' => '您无权限修改团队信息！'));
                    exit;
                }
            }
        }
        
        $tname = I('teamname');
        $url = I('logo', '');
     
        if ($url!='') {
            if (substr($url, 0, 1)==='/') {
                $url = substr($url, 1);
            }
            $dir = 'Uploads/teamlogo/' . date("Ymd") . '/';
            $logo = $dir . basename($url);
            if (!file_exists($dir)) {
                mkdir($dir, 0777, true);
            }
            if (!rename($url, $logo)) {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
            unlink($url);
        }
        
        $power = I('power');
        $uid = $this->uid;
        $weixin = I('weixin');
        $weibo = I('weibo');
        $data = array(
            'power' => $power,
            'weixin' => $weixin,
            'weibo' => $weibo,
            'uid' => $uid,
            'uptime' => time(),
        );
        if (strlen($logo)>0) {
            $data['logo'] = $logo;
        }
        
        //团队
        $tid = 0;
        $arrsql = M('team');
        $count = $arrsql->where('id='.$this->userinfo['teamid'].' and state>0')->count();
        if ($count > 0) {
            $resd = $arrsql->where("uid ='" . $uid . "'")->save($data);
            if (!$resd) {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        } else {
            $data['name'] = $tname;
            $data['ctime'] = time();
            $tid = $arrsql->add($data);
            if (!$tid) {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        }
        if($tid==0){
            $tid = $this->userinfo['teamid'];
        }
        
        //项目
        $pid = 0;
        $pname = I('pname', '未命名的项目');
        $pabstract = I('pabstract');
        $pdata = array('name'=>$pname, 'abstract'=>$pabstract);
        $tabPrj = M('project');
        $prjc = $tabPrj->where("id='".$this->userinfo['projectid']."' and state>0")->count();
        if ($prjc>0) {
            $pdata['uptime'] = time();
            $resP = $tabPrj->where("uid='".$uid."'")->save($pdata);
            if (!$resP) {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        }
        else {//新建项目
            $pdata['uid'] = $uid;
            $pdata['tid'] = $tid;
            $pdata['ctime'] = time();
            $pid = $tabPrj->add($pdata);
            if (!$pid) {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        }
        
        //更新用户表
        if ($pid==0) {
            $pid = $this->userinfo['projectid'];
        }
        $ut = array('teamid' => $tid, 'teamname' => $tname, 'projectid'=>$pid, 'projectname'=>$pname);
        $ures = M('user_info')->where('uid=' . $uid)->save($ut);
        if ($ures) {
            $userinfo = $this->userinfo;
            $userinfo['teamname'] = $tname;
            $userinfo['teamid'] = $tid;
            $userinfo['projectid']=$pid;
            $userinfo['projectname']=$pname;
            $this->userinfo = $userinfo;
        }
        
        echo json_encode(array('success' => 1, 'msg' => $tid));
        exit;
    }
    
    //解散团队
    public function dismassTeam_ajax() {
        //校验权限
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if(!$resTeam){
            echo json_encode(array('success'=>0, 'msg'=>'无权限解散团队!'));
            exit;
        }
        
        //取项目信息
        $prjTab = M('project');
        $resPrj = $prjTab->where("tid=".$resTeam['id'])->find();
        //校验项目是否为空，是否可以删除
        $resJob = M('job')->where('pid='.$resPrj['id'].' and state>0')->find();
        if($resJob){
            echo json_encode(array('success' => 0, 'msg' => "当前项目内尚有职位，不能解散!"));
            exit;
        }
        //解散
        $data = array(
            'id' => $resPrj['id'],
            'state' => 0
        );
        //标记删除项目
        $prjTab->save($data);
        //标记删除团队
        $teamTab = M('team');
        $data['id'] = $resTeam['id'];
        $resTeam = $teamTab->save($data);
        if ($resTeam) {
            //更新相关数据
            $data = array(
                'teamname'=>'',
                'projectname'=>'',
                'teamid'=>-1,
                'projectid'=>-1
            );
            $resUserinfo = M('user_info')->where('uid='.$this->uid)->save($data);
            echo json_encode(array('success'=>1, 'msg'=>'已将团队解散'));
            exit;
        }
        else{
            echo json_encode(array('success'=>0, 'msg'=>'解散失败!'));
            exit;
        }
    }

    //编辑项目信息
    public function projectinfo() {
        $teamid = I('teamid');
        if (!$teamid) {
            $this->redirect('/@'.getDomain());
        }
        $ret = parent::isTeamCreater($teamid);
        if ($ret) {
            $this->assign('creater', 1);
        }
        $where['tid'] = array('eq', $this->userinfo['teamid']);
        $where['state'] = array('gt', 0);
        $prj = M('project')->where($where)->find();
        $pcreater = 0;//是否项目创建者
        $editor = 0;//编辑项目信息权限
        $new = 1;
        if ($prj) {
            $new = 0;
            if($prj['uid']==$this->uid){
                $pcreater = 1;//只有创建者才能看见"删除项目"按钮
            }
            else{
                $resAuth = parent::teamauthcheck($this->uid, 51);//M('authdispatch')->where('arid='.$this->userinfo['role'].' and authid=51')->find();
                if($resAuth){
                    $editor = 1;
                }
            }
        }
        
        //项目是否所有职位已托管
        $moneyin = 0;//0未托管,1已托管,2已结算,3部分托管,4部分结算
        $tc = $jc = 0;//托管量和结算量
        $jobs = M('job')->where('pid='.$prj['id'].' and state>0')->select();
        foreach ($jobs as $job) {
            if ($job['moneyin']==1){
                $tc++;
            }
            if ($job['moneyin']==2) {
                $jc++;
            }
        }
        $jobAmount = count($jobs);
        if ($tc>0 && $tc<$jobAmount && $jc==0) {
            $moneyin = 3;
        }
        else if ($tc>0 && $tc==$jobAmount){
            $moneyin = 1;
        }
        else if ($jc>0 && $jc<$jobAmount) {
            $moneyin = 4;
        }
        else if ($jc>0 && $jc==$jobAmount) {
            $moneyin = 2;
        }
        $prj['moneyin'] = $moneyin;
        
        $this->assign("uid", $this->uid);
        $this->assign("userinfo", $this->userinfo);
        $this->assign("prj", $prj);
        $this->assign("new", $new);
        $this->assign('pcreater', $pcreater);
        $this->assign('editor', $editor);
        $this->assign('tip', C('PRJ_MONEY_TUOGUAN_GUIDE'));
        $this->assign('teamsubon', 2);
        
        $this->dataheader();
        
        $this->display();
    }
    
    //项目名称唯一性校验
    public function prjnamecheck_ajax() {
        $name = I('name');
        if (strlen($name)<=0) {
            echo json_encode(array('success' => 0, 'msg' => '参数错误！'));
            exit;
        }
        $resPrj = M('project')->where("name='".$name."' and state>0")->find();
        if ($resPrj) {
            echo json_encode(array('success' => 0, 'msg' => '该项目名称已被使用！'));
            exit;
        }
        echo json_encode(array('success' => 1, 'msg' => '可使用'));
        exit;
    }

    //提交项目基本信息
    public function projectinfo_ajax() {
        //权限校验
        $prjtab = M('project');
        if($this->userinfo['projectid']>-1){
            $resTeam = parent::isTeamCreater($this->userinfo['teamid']);//M('team')->where('uid='.$this->uid.' and state>0')->find();//团队
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);//$prjtab->where('uid='.$this->uid)->find();//项目
            if($resTeam){//是团队创建者
                if(!$resPrj){//不是项目创建者
                    //所在项目是否属于所在团队
                    $resPrj2 = $prjtab->where('id='.$this->userinfo['projectid'])->find();
                    if(!$resPrj2 || $resTeam['id']!=$resPrj2['tid']){
                        echo json_encode(array('success' => 0, 'msg' => '您无权限修改项目信息！'));
                        exit;
                    }
                }
            }
            else{//不是团队创建者
                if(!$resPrj){//不是项目创建者
                    $resAuth = parent::teamauthcheck($this->uid, 51);//M('authdispatch')->where('arid='.$this->userinfo['role'].' and authid=51')->find();
                    if(!$resAuth){
                        echo json_encode(array('success' => 0, 'msg' => '您无权限修改项目信息！'));
                        exit;
                    }
                }
            }
        }
        
        $name = I('name');
        $guihua = I('guihua');
        $abstract = I('abstract');
        $benefit = i('benefit');
        $data = array(
            'name' => $name,
            'guihua' => $guihua,
            'abstract' => $abstract,
            'benefit' => $benefit,
            'state' => 1,
            'uptime' => time(),
        );
        $where['tid'] = array('eq', $this->userinfo['teamid']);
        $where['state'] = array('gt', 0);
        
        $arrsql = $prjtab->where($where)->find();
        if ($arrsql) {
            //名称唯一性校验
            $resPrj = $prjtab->where("name='".$name."' and state>0")->find();
            if ($resPrj && $resPrj['id']!=$arrsql['id']){
                echo json_encode(array('success' => 0, 'msg' => '该项目名称已被使用!'));
                exit;
            }
            $resd = $prjtab->where("id ='" . $arrsql['id'] . "'")->save($data);
            if ($resd) {
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        } else {
            //名称唯一性校验
            $resPrj = $prjtab->where("name='".$name."' and state>0")->find();
            if ($resPrj){
                echo json_encode(array('success' => 0, 'msg' => '该项目名称已被使用!'));
                exit;
            }
            $data['ctime'] = time();
            $data['uid'] = $this->uid;
            $data['tid'] = $this->userinfo['teamid'];
            $res = $prjtab->add($data);
            if ($res) {
                //新建项目
                $data = array('projectname' => $name, 'projectid' => $res);
                $userinfoRes = M('user_info')->where('uid=' . $this->uid)->save($data);
                if ($userinfoRes) {
                    //重置团队表的favcount，因为目前一个团队只能有一个项目，favcount字段跟项目强关联
                    M('team')->where('id='.$this->userinfo['teamid'])->setField('favcount', 0);
                    
                    $this->userinfo['projectname'] = $name;
                    $this->userinfo['projectid'] = $res;
                    echo json_encode(array('success' => 1, 'msg' => ''));
                    exit;
                }
            }
            echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
            exit;
        }
    }

    //删除项目
    public function deleteProject_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('pid')) == false) {
            echo json_encode(array('success' => 0, 'msg' => "找不到该项目!"));
            exit;
        }
        $pid = I('pid');
        if ($pid == -1) {
            echo json_encode(array('success' => 0, 'msg' => "找不到该项目!"));
            exit;
        }
        
        //校验项目是否为空，是否可以删除
        $resJob = M('job')->where('pid='.$pid.' and state>0')->find();
        if($resJob){
            echo json_encode(array('success' => 0, 'msg' => "当前项目内尚有职位，不能删除!"));
            exit;
        }
        
        //校验当前数据状态
        $resPrj = M('project')->where('id='.$pid)->find();
        if($resPrj){
            //校验权限
            if($resPrj['uid']!=$this->uid){//非项目创建者
                $resTeam = M('team')->where('id='.$resPrj['tid'].' and state>0')->find();
                if ($resTeam['uid']!=$this->uid) {//非团队创建者
                    echo json_encode(array('success'=>0,'msg'=>'无权限删除项目!'));
                    exit;
                }
            }
            if($resPrj['state']==0){
                echo json_encode(array('success' => 1, 'msg' => '该项目已被删除'));
                exit;
            }
        }
        $data = array(
            'state' => 0,
        );
        $ret = M('project')->where('id=' . $pid)->save($data);
        if ($ret) {
            $ret = M('user_info')->where('uid=' . $this->uid)->save(array('projectname' => '', 'projectid' => -1));
            if ($ret) {
                echo json_encode(array('success' => 1, 'msg' => '成功删除该项目'));
                exit;
            }
        }
        echo json_encode(array('success' => 0, 'msg' => "删除失败!"));
        exit;
    }

    //职位管理
    public function jobs() {
        $teamid = I('teamid');
        if (!$teamid) {
            $this->redirect('/@'.getDomain());
        }
        
        //是否创建者
        $ret = parent::isTeamCreater($teamid);
        if($ret){
            $this->assign('creater', 1);
        }
        
        $where['tid'] = array('eq', $teamid);
        $where['state'] = array('gt', 0);
        $prj = M('project')->where($where)->find();
        if($prj && $prj['uid']==$this->uid){
            $this->assign('creater', 1);
        }
        
        if ($prj) {//出错或为空
            $pid = $prj['id'];
            $this->assign('pid', $pid);
        }
        
        
        //获取职位
        $jobs = M('job')->where("pid ='" . $pid . "' and state>0")->order('ctime')->select();
        if (is_array($jobs)) {
            foreach ($jobs as $i=>$job) {
                if ($job['instalment']==2) {
                    $instals = M('instal_stage')->where("jobid=".$job['id'])->select();
                    $jobs[$i]['instals'] = $instals;
                }
            }
//            dump($jobs);
//            exit;
            $this->assign('jobs', $jobs);
        }
        
        
        //权限判断
        $adder = 0;//添加部门或职位权限
        $deler = 0;//删除部门或职位权限
        //团队创建者
        $resTeam = parent::isTeamCreater($teamid);//M('team')->where('id='.$teamid.' and state>0')->find();
        if($resTeam){
            $adder = 1;
            $deler = 1;
        }
        //项目创建者
        if($prj['uid']==$this->uid){
            $adder = 1;
            $deler = 1;
        }

        $this->assign("uid", $this->uid);
        $this->assign("userinfo", $this->userinfo);
        $this->assign('adder', $adder);
        $this->assign('deler', $deler);
        $this->assign('teamsubon', 3);
        $this->assign('tip', C('PRJ_MONEY_TUOGUAN_GUIDE'));
        $this->dataheader();
        
        $this->display();
    }
    
    //职位要求
    public function jobcondition() {
        import('ORG.Util.Verify');
        if(Verify::isEmpty(I('pid'))==false
          ){
            //Log::write("pid:".Verify::isEmpty(I('pid')).",did:".Verify::isEmpty(I('did')).",id:".Verify::isEmpty(I('id')));
            echo "<script>alert('数据出错');</script>";
            exit;
        }
        $pid = I('pid');
        $jid = I('id');
        
        $resJob = M('job')->where('id='.$jid.' and state>0')->find();
        if ($resJob) {//已存在该job，则是编辑job信息
            Log::write("[jobcondition]".json_encode($resJob));
            $this->assign('job', $resJob);
        }
        
        $this->assign('pid', $pid);
        $this->assign('jid', $jid);
        $this->display();
    }

    //保存职位信息
    public function job_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                ajaxf('你无权限编辑职位信息');
            }
        }
        
        $name = I('name');
        $jobid = I('id');
        $pid = I('pid');
        $num = I('num');
        $salary = I('salary');
        $salarytype = I('salarytype', 2);//默认按项目结算
        $zhize = I('zhize');
        $yaoqiu = I('yaoqiu','未填写');
        $instalment = I('instalment');
        
        $now = time();
        
        if ($salary<500) {
            ajaxf('薪水不能小于￥500'); 
        }
        
        $data = array(
            'name' => $name,
            'salarytype' => $salarytype,
            'num' => $num,
            'zhize' => $zhize,
            'yaoqiu' => $yaoqiu,
            'instalment' => $instalment,
            'ctime' => time(),
        );
        $arrsql = M('job');
        if ($jobid > 0) {
            //编辑已有职位
            //是否已有雇员任职
            $instalArr = array();
            $ret = M('job_user')->where("jobid=".$jobid)->select();
            if (!$ret) {//无人任职，可以修改薪酬数据
                if ($instalment==1) {
                    $data['salary'] = $salary;
                }
                else if ($instalment==2) {
                    $instalArr = I('instals');
                    if (!$instalArr) {
                        ajaxf("请填写薪酬分期金额!");
                    }
                }
            }
            
            $resJob = M('job')->where('id='.$jobid." and state>0")->find();
            if (!$resJob) {
                ajaxf("没有这个职位");
            }
            if ($resJob['datastate']>$num) {
                ajaxf('新职位数量不能小于当前该职位入职人数');
            }
            $resd = $arrsql->where("id ='" . $jobid . "'")->save($data);
            if ($resd) {
                setTeamJobNum($this->userinfo['teamid'], $num-$resJob['num'], 0);//团队职位统计添加相应职位数量
                if ($instalment==2) {
                    //更新分期数据
                    $instData = '';
                    foreach ($instalArr as $item) {
                        $kv = split(':', $item);
                        $instid = $kv[0];
                        $money = $kv[1];
                        $instData .= "($instid,$money),";//"(id,amount)";
                    }
                    $allkv = substr($instData, 0, -1);
                    $sql = "INSERT INTO xia_instal_stage (id,amount) values ".$allkv." ON DUPLICATE KEY UPDATE amount=values(amount)";
                    $ret = M()->query($sql);//不校验返回值
                }
                
                ajaxs();
            } else {
                ajaxf('保存失败，请重新提交');
            }
        } else {
            //新增职位
            $data['pid'] = $pid;
            $data['did'] = 0;
            $data['state'] = 1;
            $instalArr = array();//为存储分期数组预留
            if ($instalment==1) {
                $data['salary'] = $salary;
            }
            else if ($instalment==2) {
                $instalArr = I('instals');
                if (!$instalArr) {
                    ajaxf("请填写薪酬分期金额!");
                }
            }
            $resJob = $arrsql->where("id=".$jobid." and did=0 and state>0 and pid=".$pid)->find();
            if ($resJob) {
                ajaxf("已添加相同名称职位");
            }
            $res = $arrsql->add($data);
            if ($res) {
                setTeamJobNum($this->userinfo['teamid'], $num, 0);//添加相应职位数量
                if ($instalment==2) {
                    //添加分期数据
                    $instalData = array();
                    foreach ($instalArr as $instal) {
                        $instData[] = array(
                            'jobid' => $jobid,
                            'amount' => $instal,
                            'moneyin' => \App\Common\Constvars::JOB_SALARYSTATUS_UNDELTEGETE,
                            'pay' => \App\Common\Constvars::JOB_PAY_NO,
                            'ctime' => $now
                        );
                    }
                    M('instal_stage')->addAll($instalData);//不校验返回值
                }
                
                ajaxs();
            } else {
                ajaxf('由于系统错误，添加失败');
            }
        }
    }
    
    //添加薪酬分期
    public function add_instal() {
        $jobid = I('jobid');
        $amount = I('amount');
        if (!$jobid || !$amount) {
            ajaxf("参数错误！");
        }
        $now = time();
        
        //校验,是否期数已达最高限额3期
        $tabInst = M('instal_stage');
        $insArr = $tabInst->where("jobid=".$jobid)->select();
        if ($insArr && count($insArr)>=3) {
            ajaxf("最多只能分三期");
        }
        
        $data = array(
            'jobid' => $jobid,
            'amount' => $amount,
            'income' => 0,
            'moneyin' => \App\Common\Constvars::JOB_SALARYSTATUS_UNDELTEGETE,
            'pay' => \App\Common\Constvars::JOB_PAY_NO,
            'ctime' => $now
        );
        $ret = $tabInst->add($data);
        if ($ret>0) {
            ajaxs();
        }
        else {
            ajaxf();
        }
    }
    
    //删除薪酬分期
    public function del_instal() {
        $insid = I('inst');
        if (!$insid) {
            ajaxf("参数错误！");
        }
        $tabIns = M();
        $table = array('xia_instal_stage'=>'inst');
        $join1 = "LEFT JOIN xia_job j ON j.id=inst.jobid";
        $join2 = "LEFT JOIN xia_project prj ON prj.id=j.pid";
        $join3 = "LEFT JOIN xia_team team ON team.id=prj.tid";
        $field = "inst.id as instid,j.id as jobid,prj.id as pid,team.id as tid,team.uid";
        $ret = $tabIns->table($table)->field($field)->join($join1)->join($join2)->join($join3)->where("inst.id=".$insid)->find();
        if ($ret && $ret['uid']!=$this->uid) { //权限校验
            ajaxf();
        }
        //校验是否已有雇员入职
        $tabJu = M('job_user');
        $ret = $tabJu->where("jobid=".$ret['jobid']." and state=2")->select();
        if ($ret) {
            ajaxf("已有雇员入职该职位，不能再更改职位数据");
        }
        $ret = M('instal_stage')->where("id=".$insid)->delete();
        if ($ret===FALSE) {
            ajaxf();
        }
        else {
            ajaxs();
        }
    }

    //删除职位
    public function job_del() {
        $id = I('id');
        $jobTab = M('job');
        if ($id > 0) {
            //权限校验
            $resAll = M('job')->table(array('xia_job'=>'job','xia_project'=>'prj','xia_team'=>'team'))->field('job.*,prj.uid as pleader,team.uid as tleader')->where('job.id='.$id.' and job.pid=prj.id and prj.state>0 and prj.tid=team.id and team.state>0')->find();
            if (!$resAll) {
                echo json_encode(array('success' => 0, 'msg' => '数据错误!'));
                exit;
            }
            if ($resAll['dleader']!=$this->uid && $resAll['pleader']!=$this->uid && $resAll['tleader']!=$this->uid) {
                echo json_encode(array('success' => 0, 'msg' => '无权限做此操作!'));
                exit;
            }
            $resJobuser = M('job_user')->where('jobid='.$id.' and state in (2,4,5)')->select();
            if ($resJobuser) {
                echo json_encode(array('success' => 0, 'msg' => '该职位尚有成员任职，无法删除'));
                exit;
            }
            $resd = $jobTab->where("id ='" . $id . "'")->save(array('state'=>0));
            if ($resd) {
                setTeamJobNum($this->userinfo['teamid'], -$resAll['num'], 0);//减去相应职位数量
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '操作失败，请重新提交'));
                exit;
            }
        } else {
            echo json_encode(array('success' => 0, 'msg' => '操作失败，请重新提交'));
            exit;
        }
    }

    //成员管理
    public function members() {
        $teamid = I('teamid');
        if (!$teamid) {
            $this->redirect('/@'.getDomain());
        }
        
        //获取员工
        $pid = $this->userinfo['projectid'];
        $count = M('job_user')->where('state=2 and pid=' . $pid)->count();
        $count = $count + 1;//加上创建者
        //$join = "xia_job ON xia_job_user.jobid=xia_job.id,xia_depament ON xia_job.did=xia_depament.id,xia_user ON xia_job_user.uid=xia_user.id,xia_user_info ON xia_job_user.uid=xia_user_info.uid,xia_authrole ON xia_user_info.role=xia_authrole.id";
        $field = "xia_job_user.*,xia_user.email,xia_job.name as jname,xia_authrole.name as rolename";
        $list = M('job_user')->field($field)->where('xia_job_user.state=2 and xia_job_user.pid='.$pid)->join('xia_job ON xia_job_user.jobid=xia_job.id')->join('xia_user ON xia_job_user.uid=xia_user.id')->join('xia_user_info ON xia_job_user.uid=xia_user_info.uid')->join('xia_authrole ON xia_user_info.role=xia_authrole.id')->select();
        $time = time()-C('APPLY_TIMEOUT');
        //发起辞退或者发起离职申请的成员
        $waits = M('job_user')->table(array('xia_job_user'=>'list', 'xia_job'=>'job','xia_user'=>'user', 'xia_user_info'=>'userinfo'))->field('list.*, job.name as jname, user.email,userinfo.nickname')->where('list.pid='.$pid.' and list.state in (4,5) and list.uptime>='.$time.' and list.jobid=job.id and list.uid=user.id and user.id=userinfo.uid')->select();
//        dump($waits);
//        exit;
        $this->assign('applyquit', 0);
        $this->assign('berevoked', 0);
        $this->assign('hasapply', 0);
        $this->assign('creater', 0);
        //自己是否已申请离职
        if ($waits) {
            foreach ($waits as $jobuser) {
                if ($jobuser['uid']==$this->uid) {
                    if ($jobuser['state']==5) {
                        $this->assign('applyquit', 1);
                    }
                    elseif ($jobuser['state']==4) {
                        $this->assign('berevoked', 1);
                    }
                }
                if ($jobuser['state']==4) {
                    $this->assign('hasapply', 1);
                }
            }
        }
//dump($waits);
//exit;
        //团队创始人信息
        $founder = M('team')->table(array('xia_team'=>'team', 'xia_user'=>'user', 'xia_user_info'=>'userinfo'))->field('user.email, userinfo.*')->where('team.id='.$teamid.' and team.state>0 and team.uid=user.id and user.id=userinfo.uid')->find();
        $elapse = time()-C('APPLY_TIMEOUT');
        $shenqing = M('job_user')->table(array('xia_job_user'=>'jobuser','xia_job'=>'job'))->field('jobuser.*,job.name as jname')->where('jobuser.pid=' . $pid . ' and jobuser.state=0 and jobuser.jobid=job.id and job.state>0')->select();
//dump($shenqing);
//exit;
        //获取空缺职位
        $jobs = M('job')->field('id,name,num,datastate')->where('pid='.$pid.' and num>datastate and moneyin<>2 and state>0')->select();
        //权限校验
        $fireauth = 0;//辞退权限
        $checkauth = 0;//审批申请权限
        $inviteauth = 0;//邀请别人加入权限
        if($founder['uid']==$this->uid){
            $fireauth = 1;
            $checkauth = 1;
            $inviteauth = 1;
            $this->assign('creater', 1);
        }
        else{
            $resPrj = parent::isProjectCreater($pid);//M('project')->where('id='.$pid)->find();
            if($resPrj){
                $fireauth = 1;
                $checkauth = 1;
                $inviteauth = 1;
            }
        }
        
        //合并加入申请和离职申请
        $allsq = array_merge((array)$waits, (array)$shenqing);
        
        $this->assign("uid", $this->uid);
        $this->assign("list", $list);
        $this->assign('waits', $waits);
        $this->assign('founder', $founder);
        $this->assign("shenqing", $allsq);
        $this->assign("count", $count);
        $this->assign('fireauth', $fireauth);
        $this->assign('checkauth', $checkauth);
        $this->assign('inviteauth', $inviteauth);
        $this->assign('jobs', $jobs);
        
        if($founder['uid']==$this->uid){
            $this->assign('creater', 1);
        }
        
        $this->assign('teamsubon', 4);
        
        $this->dataheader();
        
        $this->display();
    }

    //成员审核操作
    public function ctrl_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                echo json_encode(array('success'=>0, 'msg'=>'你无权限进行成员审核'));
                exit;
            }
        }
        
        $id = I('id');
        $type = I('type');
        if ($id > 0) {
            $jobuserTab = M('job_user');
            $resJobuser = $jobuserTab->where('id='.$id)->find();
            if(!$resJobuser){
                echo json_encode(array('success' => 0, 'msg' => '数据错误!'));
                exit;
            }
            
            //用户id,项目id
            $pid = $resJobuser['pid'];
            $uid = $resJobuser['uid'];
            $jobid = $resJobuser['jobid'];
            
            if ($type==2) {//批准申请
                //检查用户是否撤销
                $ret = $jobuserTab->where('uid='.$uid.' and jobid='.$jobid)->find();
                if (!$ret){
                    $this->ajaxf('该用户已撤销申请。');
                }
                //该用户是否已有团队
                $resUif = M('user_info')->where('uid='.$uid)->find();
                if ($resUif['teamid']>0) {
                    ajaxf('这个用户已加入其他团队');
                }
                
                //检查用户是否已在其他职位任职
                $resJu = $jobuserTab->where('uid='.$uid.' and (state=2 or state=4 or state=5)')->find();
                if ($resJu) {
                    $this->ajaxf('该用户已在其他项目或职位任职，不能身兼数职。');
                }
            }
            $statD = array('id' => $id,'state' => $type);
            $resd = $jobuserTab->save($statD);//设置状态
            if ($resd) {
                if ($type==2) {//入职
                    //是否满员
                    $resJob = M('job')->where('id='.$resJobuser['jobid'])->find();
                    if (!$resJob || $resJob['num']<=$resJob['datastate']) {
                        echo json_encode(array('success' => 0, 'msg' => '该职位已满员!'));
                        exit;
                    }
                    
                    $resPrj = M('project')->where('id='.$pid)->find();
                    if(!$resPrj){
                        echo json_encode(array('success' => 0, 'msg' => '数据错误!'));
                        exit;
                    }
                    $resTeam = M('team')->where('id='.$resPrj['tid'].' and state>0')->find();
                    if(!$resTeam){
                        echo json_encode(array('success' => 0, 'msg' => '数据错误!'));
                        exit;
                    }
                    //保存团队和项目信息
                    $this->jointeam_syncdata($uid, $pid, 0, $jobid);
                    
                    //发送入职通知
                    $now = time();
                    $content = "<td>喜大普奔，您申请加入<b>".$resTeam['name']."</b>，创始人已<b>同意</b>，您已成为该团队成员，还等什么，抓住机会，漂亮的完成这个项目吧！</td>";
                    $data = array(
                        'uid'=>$uid,
                        'content'=>  logPost($content, U("Team/index@".getDomain()), $now),
                        'ctime'=>$now,
                    );
                    M('office_log')->add($data);
                }
                else if ($type==3) {//拒绝加入申请
                    $now = time();
                    M('job_user')->where('uid='.$uid.' and jobid='.$jobid)->delete();
                    //发送通知
                    $resPrj = M('project')->where('id='.$pid)->find();
                    if(!$resPrj){
                        $this->ajaxf('数据错误!');
                    }
                    $resTeam = M('team')->where('id='.$resPrj['tid'].' and state>0')->find();
                    if(!$resTeam){
                        echo json_encode(array('success' => 0, 'msg' => '数据错误!'));
                        exit;
                    }
                    $content = "<td>遗憾的说，您申请加入<b>[".$resTeam['name']."]</b>被创始人拒绝，打起精神去项目库看看其他项目吧。</td>";
                    $content = logPost($content, U("Project/detail@".getDomain(), array('id'=>$pid)), $now);
                    sendNotice($uid, $content);
                }
                
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '操作失败，请重新提交'));
                exit;
            }
        } else {
            echo json_encode(array('success' => 0, 'msg' => '操作失败，请重新提交'));
            exit;
        }
    }

    //情报中心
    public function information() {
        //获取员工
        $list = M('office_log')->where('uid='.$this->uid)->order('ctime desc')->select();
        $view = M('log_view')->where('uid =' . $this->uid)->select();
        $listarr = array();
        if ($list && $view) {
            
            foreach ($list as $k => $val) {
                foreach ($view as $j => $val2) {                    
                    if ($val2['logid'] == $val['id']) {
                        $list[$k]['content'] = trimOperation($list[$k]['content']);
                        $listarr[] = $list[$k];
                        unset($list[$k]);
                    }
                }
            }
        }
        
//        dump(array($list,$view,$listarr));
//        exit;
        $this->assign("uid", $this->uid);
        $this->assign("list", $list);
        $this->assign("listold", $listarr);
        $this->assign('on',3);
        
        $this->dataheader();
        
        $this->display();
    }

    //情报中心操作
    public function log_ajax() {
        $uid = I('uid');
        $logid = I('logid');
        $data = array(
            'uid' => $uid,
            'logid' => $logid,
        );
        $resd = M('log_view')->add($data);
        if ($resd) {
            echo json_encode(array('success' => 1, 'msg' => ''));
            exit;
        } else {
            echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
            exit;
        }
    }
    
    //设置所有最新情报为已读
    public function readallog_ajax() {
        $list = M('office_log')->where('uid='.$this->uid)->order('ctime desc')->select();
        $view = M('log_view')->where('uid =' . $this->uid)->select();
        $listarr = array();
        foreach ($list as $k => $val) {
            $ifin = false;
            foreach ($view as $j => $val2) {
                if ($val2['logid'] == $val['id']) {
                    $ifin = true;
                }
            }
            if (!$ifin) {
                $listarr[] = array(
                    'uid'=>  $this->uid,
                    'logid' => $val['id'],
                );
            }
        }
        $resd = M('log_view')->addAll($listarr);
        if ($resd) {
            $this->ajaxs();
        } else {
            $this->ajaxf('设置失败!');
        }
    }
    
    //删除情报
    public function delinfo_ajax() {
        $id = I('info', 0);
        $ret = M('office_log')->where('id='.$id.' and uid='.$this->uid)->delete();
        if ($ret) {
            M('log_view')->where('uid='.$this->uid.' and logid='.$id)->delete();
            ajaxs(1, '成功删除这条情报!');
        }
        else {
            ajaxf('删除这条情报的时候发生错误!');
        }
    }
    
    //清空已读情报
    public function clearlogview_ajax() {
        $logviewlist = M('log_view')->where('uid='.$this->uid)->select();
        if ($logviewlist) {
            $ret = M('office_log')->where('id in (select logid from xia_log_view where uid='.$this->uid.')')->delete();
            if ($ret) {
                M('log_view')->where('uid='.$this->uid)->delete();
                ajaxs();
            }
        }
        ajaxf('无已读情报');
    }

    //创建&编辑任务
    public function renwu() {
        $id = I('id');
        if (!$id) {
            $id = 0;
        }
        $renwu = M('renwu')->where("pid ='" . $id . "'")->select();
        $renwu_data = M('renwu_data')->where("pid ='" . $id . "'")->select();
        $v = array();
        foreach ($renwu as $val) {
            $val['data'] = array();
            foreach ($renwu_data as $val2) {
                if ($val2['rid'] == $val['id']) {
                    $val['data'][] = $val2;
                }
            }
            $v[] = $val;
        }
        //dump($v);
        $this->assign("uid", $this->uid);
        $this->assign("userinfo", $this->userinfo);
        $this->assign("arr", $renwu);
        $this->assign("renwu_data", $v);
        $this->assign("id", $id);
        
        $this->dataheader();
        
        $this->display();
    }

    //提交任务标题
    public function renwu_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                $ret = parent::teamauthcheck($this->uid, 76);
                if (!$ret) {
                    echo json_encode(array('success'=>0, 'msg'=>'你无权限添加或编辑任务'));
                    exit;
                }
            }
        }
        
        $id = I('id', 0);
        $pid = I('pid');
        $name = I('name');
        $data = array(
            'pid' => $pid,
            'name' => $name,
            'ctime' => time(),
        );
        $arrsql = M('renwu');
        if ($id > 0) {
            $resd = $arrsql->where("id ='" . $id . "'")->save($data);
        } else {
            $resd = $arrsql->add($data);
        }
        if ($resd) {
            echo $resd;
            exit;
        } else {
            echo 0;
            exit;
        }
    }

    //添加、提交任务信息
    public function renwu_data_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                $ret = parent::teamauthcheck($this->uid, '72,76');
                if (!$ret) {
                    echo json_encode(array('success'=>0, 'msg'=>'你无权限添加或编辑任务'));
                    exit;
                }
            }
        }
        
        $id = I('id', 0);
        $roleid = I('roleid');
        $rolename = I('rolename');
        $title = I('title');
        $deadline = I('deadline');
        $info = I('info');
        $depament = I('depament');
        $depamentid = I('depamentid');
        $state = I('state');
        $data = array(
            'roleid' => $roleid,
            'rolename' => $rolename,
            'title' => $title,
            'deadline' => $deadline,
            'depament' => $depament,
            'depamentid' => $depamentid,
            'state' => $state,
            'ctime' => time(),
        );
        $arrsql = M('project');
        if ($id > 0) {
            $resd = $arrsql->where("id ='" . $id . "'")->save($data);
            if ($resd) {
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        } else {
            $data['ctime'] = time();
            //dump($data);
            $res = $arrsql->add($data);
            if ($res) {
                echo json_encode(array('success' => 1, 'msg' => ''));
                exit;
            } else {
                echo json_encode(array('success' => 0, 'msg' => '保存失败，请重新提交'));
                exit;
            }
        }
    }
    
    //拉取用户权限设置
    public function getroleauth_ajax() {
        $roleid = I('roleid');
        if(!$roleid){
            exit;
        }
        //角色权限
        $roleauth = M('authdispatch')->where('arid='.$roleid)->select();
        //团队事务权限
        $teamAuth = M('dic')->where('type=3')->select();
        for ($i=0;$i<count($teamAuth);$i++) {
            if($roleauth){
                foreach($roleauth as $role){
                    if($teamAuth[$i]['id']==$role['authid']){
                        $teamAuth[$i]['flag'] = true;
                    }
                }
            }
        }
        //项目事务权限
        $prjAuth = M('dic')->where('type=4')->select();
        //赋予顺序编码
        $orderCode = array(1,4,3,5,2);
        for ($i = 0; $i < count($prjAuth); $i++) {
            $prjAuth[$i]['oc'] = $orderCode[$i];
        }
        $cmp_func = function($prjL, $prjR){return $prjL['oc']-$prjR['oc'];};
        usort($prjAuth, $cmp_func);
        for($i=0;$i<count($prjAuth);$i++){
            if($roleauth){
                foreach ($roleauth as $role) {
                    if($prjAuth[$i]['id']==$role['authid']){
                        $prjAuth[$i]['flag'] = true;
                    }
                }
            }
        }
        
        $this->assign('roleid', $roleid);
        $this->assign('teamAuth',$teamAuth);
        $this->assign('prjAuth',$prjAuth);
        echo $this->fetch('authlist');
    }
    
    //保存用户权限设置
    public function saveroleauth_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                echo json_encode(array('success'=>0,'msg'=>'无权限做此操作!'));
                exit;
            }
        }
        
        $arid = I('roleid');
        $authArray = I('choose');
        
        $tab = M('authdispatch');
        $ret = $tab->where('arid='.$arid)->delete();
        import('ORG.Util.Verify');
        if($authArray==NULL){
            echo json_encode(array('success'=>1,'msg'=>'no choose'));
            exit;
        }
        $data = array();
        foreach ($authArray as $auth) {
            if ($auth>=70 && $auth<=76) {
                $data[] = array('arid'=>$arid, 'teamid'=>$this->userinfo['teamid'], 'authid'=>$auth);
            }
        }
        $res = $tab->addAll($data);
        if( $res){
            echo json_encode(array('success'=>1));
            exit;
        }
        echo json_encode(array('success'=>0));
        exit;
    }
    
    //邀请站内用户加入团队
    public function invitjoin_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                $this->jsonpf('无权限做此操作!');
            }
        }
        
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('targetuid'))==false
            || Verify::isEmpty(I('uname'))==false
            || Verify::isEmpty(I('jobid'))==false) {
            $this->jsonpf('数据出错');
        }
        $targetuid = I('targetuid');
        $pid = $this->userinfo['projectid'];
        $did = I('did', 0);
        $jobid = I('jobid');
        $uname = I('uname');
        //该职位是否已托管
        $resJob = M('job')->where('id='.$jobid)->find();
        if (!$resJob) {
            ajaxf('找不到该职位！');
        }
//        if ($resJob['moneyin']==0) {//暂时取消托管限制 2015-11-20
//            ajaxf('这个职位薪酬尚未托管,不能邀请入职');
//        }
        
        $data = array(
            'uid'=>$targetuid,
            'pid'=>$pid,
            'did'=>$did,
            'jobid'=>$jobid,
            'state'=>1,
            'uname'=>$uname
        );
        $resJobuser = M('job_user')->add($data);
        if (!$resJobuser) {
            $this->jsonpf('已经邀请过对方!');
        }
        //给用户发情报
        $content = "<b>".$this->userinfo['nickname']."</b>邀请您加入TA的团队<a href='".U("Project/detail@".getDomain(), array('id'=>$this->userinfo['projectid']))."'><b>".$this->userinfo['teamname']."</b></a>，";
        $link = "心动就<a class='acceptInvite' href='javascript:void(0);' data-pid='".$pid."' data-jid='".$jobid."' data-rid='1' data-sid='".$this->uid."'><b>[接受邀请]</b></a>，不喜欢就<a class='acceptInvite' href='javascript:void(0);' data-pid='".$pid."' data-jid='".$jobid."' data-rid='2' data-sid='".$this->uid."'><b>[拒绝]</b></a>";
        $fullmsg = logPost('<td>'.$content.$link.'</td>', "", time(), "设为已读");
        sendNotice($targetuid, $fullmsg);
        //邮件通知
        $resUser = M('user')->table(array('xia_user'=>'user', 'xia_user_info'=>'userinfo'))->field('user.*, userinfo.nickname')->where('user.id='.$targetuid.' and user.id=userinfo.uid')->find();
        $body = composeMailHtml('亲爱的'.$resUser['nickname'], $content.',<a href="'.U("/Team/information@".getDomain()).'">快去看看吧</a>');
        $body = mailPostfix($body);
        mailqueue_push($resUser['email'], $resUser['nickname'], '邀请你加入团队', $body);
        
        $this->jsonps(1, "已经向对方发出邀请，请等待对方答复");
    }
    
    //接受\拒绝邀请
    public function acceptInvite_ajax() {
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('prj'))==false
            || Verify::isEmpty(I('job'))==false
            || Verify::isEmpty(I('r'))==false
            || Verify::isEmpty(I('s'))==false) {
            echo json_encode(array('success'=>0,'msg'=>'参数错误！'));
            exit;
        }
        $pid = I('prj');
        $jobid = I('job');
        $r = I('r');//接受or拒绝
        $s = I('s');//发送者uid
        
        //是否已有团队
        if ($this->userinfo['teamid']>0) {
            ajaxf('您已有团队，不能接受这个邀请');
        }
        $msg = "";
        //是否邀请过
        $jobuserTab = M('job_user');
        $resJobuser = $jobuserTab->where('uid='.$this->uid.' and state=1')->find();
        if (!$resJobuser) {
            echo json_encode(array('success'=>0,'msg'=>'未曾邀请过你！'));
            exit;
        }
        $now = time();
        $resJob = M('job')->where('id='.$jobid)->find();
        if ($resJob['num']==$resJob['datastate']) {//满员
            //删除job_user记录
            $jobuserTab->where('id='.$resJobuser['id'])->delete();
            ajaxf("很遗憾，该职位有别人已加入且已满员，你目前无法加入。");
        }
        $resPrj = M('project')->where('id='.$resJob['pid'].' and state>0')->find();
        if ($r==1) {
            $ret = $jobuserTab->where('uid='.$this->uid.' and state=1')->setField('state', 2);
            if (!$ret) {
                echo json_encode(array('success'=>0,'msg'=>'加入失败！'));
                exit;
            }

            $teamid = $this->jointeam_syncdata($this->uid, $pid, 0, $jobid);
            if ($teamid==0) {
                $this->ajaxf('加入对方团队失败');
            }
            $content = '<td>喜大普奔！您向<a href="javascript:void(0);" data-url="'.genTalentURL($this->uid).'"><b>'.$this->userinfo['nickname'].'</b></a>发出的<b>'.$resJob['name'].'</b>邀请，已成功吸引TA加入您的团队。</td>';
            $content = logPost($content, U("Team/members@".getDomain(), array('teamid'=>$teamid)), $now);
            sendNoticeBatch($this->uid, $teamid, $pid, $content);
            $msg = "成功加入团队";
        }
        else if ($r==2) {
            $jobuserTab->where('uid='.$this->uid.' and state=1')->delete();
            //通知发送者，邀请被拒绝
            $content = '<td>遗憾的说，您向<a href="javascript:void(0);" data-url="'.genTalentURL($this->uid).'"><b>'.$this->userinfo['nickname'].'</b></a>发出的<b>'.$resJob['name'].'</b>邀请被残忍拒绝了。</td>';
            $content = logPost($content, "", $now);
            sendNotice($s, $content);
            $msg = "已拒绝对方的邀请";
        }
        
        echo json_encode(array('success'=>1,'msg'=>$msg));
        exit;
    }
    
    //申请离职
    public function applyquit_ajax() {
        $now = time();
        //向管理层发送申请
        $data = array(
            'state'=>5,
            'uptime'=>$now,
        );
        $ret = M('job_user')->where('uid='.$this->uid)->save($data);
        if (!$ret) {
            echo json_encode(array('success'=>0, 'msg'=>'申请失败！'));
            exit;
        }
        
        $msg = "<td>遗憾的说，您的团队成员<a href='javascript:void(0);' data-url=\"".genTalentURL($this->uid)."\"><b>".$this->userinfo['nickname']."</b></a>申请离职,请尽快与TA沟通。</td>";
        $data = array(
            'content'=>  logPost($msg,U("Team/members@".getDomain(), array('teamid'=>$this->userinfo['teamid'])), $now),
            'ctime'=>$now,
        );
        //管理层
        $resTeam = M('team')->where('id='.$this->userinfo['teamid'])->find();
        if ($resTeam){
            $data['uid'] = $resTeam['uid'];
        }
        $ret = M('office_log')->add($data);
        
        //发送邮件给管理层
        $subject = "申请离职";
        $resUser = M('user')->table(array('xia_user'=>'user','xia_user_info'=>'userinfo'))->field('user.*,userinfo.nickname,userinfo.teamid,userinfo.teamname')->where('user.id='.$data['uid'].' and user.id=userinfo.uid')->find();
        $body = "亲爱的".$resUser['nickname'].",<br/>&nbsp;&nbsp;&nbsp;&nbsp;你的团队有成员提出了离职申请，";
        $body .= "<a href='".U("/Team/members@".getDomain(), array("teamid"=>$resUser['teamid']))."'>快去看看</a>吧";
        $body = mailPostfix($body);
        mailqueue_push($resUser['email'], $resUser['nickname'], $subject, $body);
        
        echo json_encode(array('success'=>1, 'msg'=>'已向leader发出申请'));
        exit;
    }
    
    //辞退成员
    public function firemployee_ajax() {
        $now = time();
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                echo json_encode(array('success'=>0,'msg'=>'无权限做此操作!'));
                exit;
            }
        }
        
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('uid'))==false) {
            echo json_encode(array('success'=>0, 'msg'=>'参数错误'));
            exit;
        }
        $uid = I('uid');
        $data = array(
            'state' => 4,
            'uptime' => $now,
        );
        $ret = M('job_user')->where('uid='.$uid)->save($data);
        if($ret){
            //发送站内消息给被辞退成员
            $log = "<td>您的团队创始人<a href='javascript:void(0);' data-url=\"".genTalentURL($this->uid)."\"><b>[".$this->userinfo['nickname']."]</b></a>对您做了<b>辞退</b>处理，3个自然日内你可以与TA沟通，如果沟通顺畅，TA可以撤销对你的辞退处理。</td>";
            $data = array(
                'uid'=>$uid,
                'content'=>  logPost($log, U("Team/members@".getDomain(), array('teamid'=>$this->userinfo['teamid'])), $now),
                'ctime'=>$now,
            );
            $resLog = M('office_log')->add($data);
            //发送邮件给被辞退成员
            $resUser = M('user')->table(array('xia_user'=>'user','xia_user_info'=>'userinfo'))->field('user.*,userinfo.nickname,userinfo.teamid,userinfo.teamname')->where('user.id='.$uid.' and user.id=userinfo.uid')->find();
            $body = "亲爱的的".$resUser['nickname'].',<br/>&nbsp;&nbsp;&nbsp;&nbsp;你所在的团队'.$resUser['teamname']."的管理层对你做了辞退处理。你";
            $body .= "<a href='".U("/Team/members@".getDomain(), array("teamid"=>$resUser['teamid']))."'>快去看看</a>吧！";
            $body = mailPostfix($body);
            mailqueue_push($resUser['email'], $resUser['nickname'], '辞退信', $body);//压入队列
            
            echo json_encode(array('success'=>1, 'msg'=>'已发出辞退操作!'));
            exit;
        }
        echo json_encode(array('success'=>0, 'msg'=>'操作失败！'));
        exit;
    }
    
    //撤销辞退
    public function revokefire_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                echo json_encode(array('success'=>0,'msg'=>'无权限做此操作!'));
                exit;
            }
        }
        
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('uid'))==false) {
            echo json_encode(array('success'=>0, 'msg'=>'参数错误'));
            exit;
        }
        $uid = I('uid');
        $juTab = M('job_user');
        $resFire = $juTab->where('uid='.$uid.' and state=4')->find();
        
        if ($resFire) {
            $elapse = time()-$resFire['uptime'];
            if ($elapse>0 && $elapse<C('APPLY_TIMEOUT')) {//未超过3个自然日
                //权限校验
                $resTeam = M('team')->where('id='.$this->userinfo['teamid'])->find();
                if ($resTeam['uid']!=$this->uid) {
                    $resPrj = M('project')->where('id='.$this->userinfo['projectid'])->find();
                    if ($resPrj['uid']!=$this->uid) {
                        echo json_encode(array('success'=>0, 'msg'=>'无权限做此操作!'));
                        exit;
                    }
                }
                $ret = $juTab->where('uid='.$uid.' and state=4')->setField('state', 2);
                if ($ret) {
                    //向人才发通知
                    $content = "<td>哇哦，您的团队创始人已经<b>撤销</b>对您的辞退，还等什么，抓住机会，漂亮的完成这个项目吧！</td>";
                    $content = logPost($content, "", time(), "设为已读");
                    sendNotice($uid, $content);
                    
                    echo json_encode(array('success'=>1, 'msg'=>'已重新将该人才加入到团队!'));
                    exit;
                }
            }
            else{
                //超出3天，退出团队
                $juTab->where('uid='.$uid.' and state=4')->delete();
                $data = array(
                    'teamname' => '',
                    'teamid'=> '-1',
                    'projectname' => '',
                    'projectid' => '-1',
                );
                M('user_info')->where('uid='.$uid)->save($data);
                echo json_encode(array('success'=>0, 'msg'=>'超出3个自然日,该用户已退出团队！'));
                exit;
            }
        }
        echo json_encode(array('success'=>0, 'msg'=>'撤销失败!'));
        exit;
    }
    
    //接受辞退
    public function acceptfire_ajax() {
        
        $resJobuser = M('job_user')->where('uid='.$this->uid.' and state=4')->find();
        if (!$resJobuser) {
            echo json_encode(array('success'=>0, 'msg'=>'数据错误'));
            exit;
        }
        $ret = M('job_user')->where('id='.$resJobuser['id'])->delete();
        if (!$ret) {
            echo json_encode(array('success'=>0, 'msg'=>'接受失败！'));
            exit;
        }
        //记入任职历史
        $resJob = M('job')->where("id=".$resJobuser['jobid'])->find();
        $quitype = \App\Common\Constvars::JOBHIS_QUITYPE_UNSETTLE;
        if ($resJob['moneyin']==\App\Common\Constvars::JOB_SALARYSTATUS_SETTLE) {
            $quitype = \App\Common\Constvars::JOBHIS_QUITYPE_SETTLE;
        }
        $jobhistory = array(
            'quitype' => $quitype,
            'quitime' => time()
        );
        M('jobhistory')->where("uid=".$this->uid." and jobid=".$resJobuser['jobid']." and quitime='0'")->save($jobhistory);
        //用户信息
        $data = array(
            'projectname'=>'',
            'projectid'=>-1,
            'teamname'=>'',
            'teamid'=>-1,
        );
        M('user_info')->where('uid='.$this->uid)->save($data);
        //更新session
        $teamid = $this->userinfo['teamid'];
        $this->userinfo['projectname'] = '';
        $this->userinfo['projectid'] = -1;
        $this->userinfo['teamname'] = '';
        $this->userinfo['teamid'] = -1;
        //职位统计
        M('job')->where('id='.$resJobuser['jobid'])->setDec('datastate');
        M('team')->where('id='.$this->userinfo['teamid'])->setDec('jobsok');
        //发送通知
        $content = "<td>用户<a href=\"javascript:void(0);\" data-url=\"".genTalentURL($this->uid)."\"><b>".$this->userinfo['nickname']."</b></a>接受辞退，已退出团队。</td>";
        $content = logPost($content, U("/Team/members@".getDomain(),array("teamid"=>$teamid)), time());
        sendNoticeBatch($this->uid, $this->userinfo['teamid'], $this->userinfo['pid'], $content, true, true, true);
        
        echo json_encode(array('success'=>1, 'msg'=>'你已退出团队!'));
        exit;
    }
    
    //同意离职申请
    public function agreequit_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                echo json_encode(array('success'=>0,'msg'=>'无权限做此操作!'));
                exit;
            }
        }
        
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('uid'))==false) {
            echo json_encode(array('success'=>0, 'msg'=>'参数错误'));
            exit;
        }
        
        $uid = I('uid');
        $juTab = M('job_user');
        $resFire = $juTab->where('uid='.$uid.' and state=5')->find();

        if ($resFire) {
            $uif = $this->userinfo;
            //退出,清理数据
            $juTab->where('uid='.$uid.' and state=5')->delete();
            $data = array(
                'teamname' => '',
                'teamid'=> '-1',
                'projectname' => '',
                'projectid' => '-1',
            );
            M('user_info')->where('uid='.$uid)->save($data);
            //历史记录离职时间
            $resJob = M('job')->where("id=".$resFire['jobid'])->find();
            $quitype = \App\Common\Constvars::JOBHIS_QUITYPE_UNSETTLE;
            if ($resJob['moneyin']==\App\Common\Constvars::JOB_SALARYSTATUS_SETTLE) {
                $quitype = \App\Common\Constvars::JOBHIS_QUITYPE_SETTLE;
            }
            $jhD = array('quitype'=>$quitype,'quitime'=>time());
            M('jobhistory')->where("uid=".$uid." and jobid=".$resFire['jobid']." and quitime='0'")->save($jhD);
            
            //发通知
            $content = "<td>您的团队创始人已<b>同意</b>您的离职申请，您已退出原团队<a href='javascript:void(0);' data-url=\"".genJobURL($uif['projectid'])."\"><b>[".$uif['teamname']."]</b></a></td>";
            $content = logPost($content, "", time(), "设为已读");
            sendNotice($uid, $content);
            
            $elapse = time()-$resFire['uptime'];
            Log::write('[同意离职申请]elapse:'.$elapse);
            if ($elapse>0 && $elapse<C('APPLY_TIMEOUT')) {//未超过3个自然日
                //修改职位席位统计
                Log::write("[同意离职申请]减少席位占据");
                M('job')->where('id='.$resFire['jobid'])->setDec('datastate');
                //修改团队职位总席位统计
                setTeamJobNum($this->userinfo['teamid'], 0, -1);
                
                echo json_encode(array('success'=>1, 'msg'=>'该离职申请已通过!'));
                exit;
            }
            else{
                //超出3天，退出团队
                echo json_encode(array('success'=>1, 'msg'=>'超出3个自然日,该用户已自动离职！'));
                exit;
            }
        }
        else{
            echo json_encode(array('success'=>1, 'msg'=>'超出3个自然日,该用户已自动离职！'));
            exit;
        }
    }
    
    //拒绝离职申请
    public function rejectquit_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                echo json_encode(array('success'=>0,'msg'=>'无权限做此操作!'));
                exit;
            }
        }
        
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('uid'))==false) {
            echo json_encode(array('success'=>0, 'msg'=>'参数错误'));
            exit;
        }
        
        $uid = I('uid');
        $juTab = M('job_user');
        $resFire = $juTab->where('uid='.$uid.' and state=5')->find();
        
        if ($resFire) {
            $elapse = time()-$resFire['uptime'];
            if ($elapse>C('APPLY_TIMEOUT')) {//超过3个自然日
                //退出,清理数据
                $juTab->where('uid='.$uid.' and state=5')->delete();
                $data = array(
                    'teamname' => '',
                    'teamid'=> '-1',
                    'projectname' => '',
                    'projectid' => '-1',
                );
                M('user_info')->where('uid='.$uid)->save($data);
                echo json_encode(array('success'=>1, 'msg'=>'已超过3天等待时间，该用户自动离职!'));
                exit;
            }
            else{
                $ret = $juTab->where('uid='.$uid.' and state=5')->setField('state', 2);
                if ($ret) {
                    //向申请者发通知
                    $now = time();
                    $resUser = M('uid='.$uid)->find();
                    $logTab = M('office_log');
                    $content = "<td>您的离职申请被团队创始人<b>拒绝</b>，您仍然是该团队成员。如有需要，您可以与TA进一步沟通。</td>";
                    $data = array(
                        'uid'=>$uid,
                        'content'=>  logPost($content, U("Team/members@".getDomain(), array('teamid'=>$resUser['teamid'])), $now),
                        'ctime'=>$now,
                    );
                    $logTab->add($data);
                    
                    echo json_encode(array('success'=>1, 'msg'=>'已拒绝该用户申请，该用户依然是团队成员!'));
                    exit;
                }
                else{
                    echo json_encode(array('success'=>0, 'msg'=>'审批失败!'));
                    exit;
                }
            }
        }
        echo json_encode(array('success'=>0, 'msg'=>'数据错误!'));
        exit;
    }
    
    //向站外人员发送邮件邀请
    public function mailInvite_ajax() {
        //权限校验
        $resTeam = parent::isTeamCreater($this->userinfo['teamid']);
        if (!$resTeam) {
            $resPrj = parent::isProjectCreater($this->userinfo['projectid']);
            if (!$resPrj) {
                echo json_encode(array('success'=>0,'msg'=>'无权限做此操作!'));
                exit;
            }
        }
        
        import('ORG.Util.Verify');
        if (Verify::isEmpty(I('email'))==false
            || Verify::isEmpty(I('job'))==false) {
            echo json_encode(array('success'=>0, 'msg'=>'参数错误'));
            exit;
        }
        $email = I('email');
        $jobid = I('job');
        $content = '';
        if (Verify::isEmpty(I('content'))==true) {
            $content = I('content');
        }
        
        $resJob = M('job')->where('id='.$jobid.' and state>0')->find();
        if (!$resJob) {
            echo json_encode(array('success'=>0, 'msg'=>'找不到该职位'));
            exit; 
        }
//        if ($resJob['moneyin']==0) {//暂时取消托管限制 2015-11-20
//            ajaxf('这个职位薪酬尚未托管，不能邀请人才入职');
//        }
        
        $now = time();
        $token = md5($email.$now);
        $link = U("/Index/join@".getDomain(), array("token"=>$token));
        
        $text = "亲爱的朋友，<br/>您的朋友".$this->userinfo['nickname']."在般若虾发布了\"".$this->userinfo['teamname']."\"的项目，现邀请您加入他的团队,出任\"".$resJob['name']."\"。";
        if ($content!='') {
            $text .= "猜猜TA对您说了什么？<br/>".$content;
        }
        $text .= "<br/><br/>";
        $text .= "请点击此链接，即刻加入般若虾，开启中高端脑力兼职之路！<br/>";
        $text .= "<a href='$link'>$link</a>";
        $text = mailPostfix($text);
        $ret = think_send_mail($email, '亲爱的朋友', '来自般若虾的邀请函——中高端脑力兼职', $text);
        if (!$ret) {
            echo json_encode(array('success'=>0, 'msg'=>'发送失败!'));
            exit;
        }
        
        //入库
        $data = array(
            'token'=>  $token,
            'sender'=>  $this->uid,
            'receiver'=> $email,
            'tid'=>  $this->userinfo['teamid'],
            'pid'=>  $this->userinfo['projectid'],
            'did'=>  0,
            'jid'=>  $jobid,
            'timepoint'=>  $now,
        );
        $ret = M('mailinvite')->add($data);
        if (!$ret) {
            echo json_encode(array('success'=>0, 'msg'=>'发送失败!'));
            exit;
        }
        echo json_encode(array('success'=>1, 'msg'=>'已向你的好友发送邀请!'));
        exit;
    }
    
    public function salary(){
        //权限校验
        if (parent::isTeamCreater($this->userinfo['teamid']) || parent::isProjectCreater($this->userinfo['projectid'])) {
            $this->assign('creater', 1);
        }
        
        $unconfirmedPay = array();
        $confirmedPay = array();
        $ped = array();
        $where = 'j.pid='.$this->userinfo['projectid'].' and j.state>0 and j.id=ju.jobid and ju.state=2';
        $members = M('job_user')->table(array('xia_job'=>'j','xia_job_user'=>'ju'))->field('j.name,j.salary,j.moneyin,ju.id,ju.uname,ju.pay')->where($where)->select();
//        echo $members;
//        exit;
        foreach ($members as $member) {
            if ($member['pay']==0) {
                $unconfirmedPay[] = $member;
            }
            if ($member['pay']==1) {
                $confirmedPay[] = $member;
            }
            if ($member['pay']==2) {
                $ped[] = $member;
            }
        }
        
        $this->assign('unced', $unconfirmedPay);
        $this->assign('ced', $confirmedPay);
        $this->assign('ped', $ped);
        
        $this->assign('teamsubon', 6);
        $this->dataheader();
        $this->display();
    }
    
    //paysalary_ajax
    public function paysalary_ajax() {
        if (!parent::isTeamCreater($this->userinfo['teamid']) && !parent::isProjectCreater($this->userinfo['projectid'])) {
            ajaxf('您没有发薪权限');
        }
        
        $juidlist = I('jobs');
        if ($juidlist==NULL) {
            ajaxf('参数为空');
        }
        //Log::write('[paysalary_ajax]juidlist:'.json_encode($juidlist), Log::ERR);
        $idstr = '';
        $len = count($juidlist);
        for ($i = 0; $i < $len; $i++) {
            if ($i!=$len-1) {
                $idstr .= $juidlist[$i].',';
            }
            else {
                $idstr .= $juidlist[$i];
            }
        }
        $tabJU = M('job_user');
        //$ret = $tabJU->where('id in ('.$idstr.') and pid='.$this->userinfo['projectid'])->setField('pay', 1);
        $sql = "UPDATE `xia_job_user` SET `pay`=1 WHERE ( id in (".$idstr.") and pid=".$this->userinfo['projectid']." )";
        $ret = $tabJU->execute($sql);
        //Log::write("[paysalary_ajax]lastSql:".$tabJU->getLastSql(), Log::ERR);
        if ($ret) {
            ajaxs(1, '已通知客服发放薪酬');
        }
        else {
            ajaxf('操作失败!');
        }
    }
    
    //情报处理统一入口
    public function dealinfo_ajax() {
        $infoID = I('infoID');
        $resLog = M('office_log')->where("id=".$infoID." and uid=".$this->uid)->find();
        if (!$resLog) {
            ajaxf("数据错误!");
        }
        $resLogView = M('log_view')->where("uid=".$this->uid." and logid=".$infoID)->find();
        if ($resLogView) {
            ajaxs();
        }
        //设置为已读
        $data = array(
            'uid' => $this->uid,
            'logid' => $infoID,
        );
        $resd = M('log_view')->add($data);
        if (!$resd) {
            ajaxf("未能成功阅读情报!");
        }
        else{
            ajaxs();
        }
    }
}

?>
